import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './index.css'

export default class Search extends Component {
  inputRef = React.createRef()

  // 点击搜索
  handleSearch = async () => {
    const inputValue = this.inputRef.current.value

    // 方法一：
    // fetch(`http://localhost:3000/api1/search/users2?q=${inputValue}`)
    //   .then((res) => {
    //     return res.json()
    //   })
    //   .then((res) => {
    //     console.log('data-->', res)
    //   })
    //   .catch(() => {
    //     console.log('出错了')
    //   })

    // 方法二
    try {
      PubSub.publish('updateListSomeStatus', {
        isFirst: false,
        isLoading: true
      })
      const response = await fetch(
        `http://localhost:3000/api1/search/users2?q=${inputValue}`
      )
      const result = await response.json()
      PubSub.publish('updateListSomeStatus', { list: result.items || [] })
    } catch (error) {
      PubSub.publish('updateListSomeStatus', {
        errInfo: '错误信息',
        list: []
      })
    } finally {
      PubSub.publish('updateListSomeStatus', { isLoading: false })
    }
  }

  render() {
    return (
      <div className="search-box">
        <h2>我是搜索段落标题</h2>
        <input ref={this.inputRef} type="text" placeholder="输入关键字" />
        <button onClick={this.handleSearch}>搜索</button>
      </div>
    )
  }
}
